package com.pfs.internal.timestamp.repositories;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;

import com.pfs.internal.timestamp.actions.TimeStampAction;
import com.pfs.internal.timestamp.entities.History;

public class HistoryRepositoryImpl extends BaseRepository<History, Integer> implements HistoryRepository {
	@SuppressWarnings("unchecked")
	public List<History> searchTracks(Map<String, Object> mapParams) {
		String account = null;
		Date fromDate = null, toDate = null;
		boolean handOnly = false;
		if (mapParams.containsKey(TimeStampAction.ACCOUNT) && mapParams.get(TimeStampAction.ACCOUNT) != null) {
			account = (String) mapParams.get(TimeStampAction.ACCOUNT);
		}
		if (mapParams.containsKey(TimeStampAction.FROM_DATE) && mapParams.get(TimeStampAction.FROM_DATE) != null) {
			fromDate = (Date) mapParams.get(TimeStampAction.FROM_DATE);
		}
		if (mapParams.containsKey(TimeStampAction.TO_DATE) && mapParams.get(TimeStampAction.TO_DATE) != null) {
			toDate = (Date) mapParams.get(TimeStampAction.TO_DATE);
		}
		if(mapParams.containsKey(TimeStampAction.HAND_ONLY)) {
			handOnly = (Boolean) mapParams.get(TimeStampAction.HAND_ONLY);
		}
		StringBuilder sb = new StringBuilder();
		sb.append("select h from History h join fetch h.cardHolder WHERE h.cardHolder.deleted = 0 AND h.cardHolder.lastName like 'PFS-%' AND h.deleted = 0");
		if(handOnly) {
			//sb.append(" AND  h.link1 = 31");
			sb.append(" AND  h.link1 in (31, 32, 34, 35, 37, 38, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 56, 57)");
		}
		//sb.append(" AND  h.cardHolder.deleted = 0");
		if (StringUtils.isNotBlank(account)) {
			sb.append(" AND  lower(h.cardHolder.lastName) like :lastName");
		}
		if (fromDate != null) {
			sb.append(" AND  h.timeStamp >= :fromDate");
		}
		if (toDate != null) {
			sb.append(" AND  h.timeStamp <= :toDate");
		}
		sb.append(" order by h.cardHolder.lastName, h.timeStamp");
		Query query = entityManager.createQuery(sb.toString());
		if (StringUtils.isNotBlank(account)) {
			query.setParameter("lastName", "%" + account.toLowerCase() + "%");
		}

		if (fromDate != null) {
			query.setParameter("fromDate", fromDate);
			System.out.println(fromDate);
		}
		if (toDate != null) {
			
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(toDate);
			calendar.add(Calendar.DAY_OF_MONTH, 1);
			query.setParameter("toDate", calendar.getTime());
			System.out.println(calendar);
			
		}
		
		System.out.println(new Date());
		List<History> list = query.getResultList();
		System.out.println(new Date());
		System.out.println(list.size());
		return list;
	}
}
